/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.javanile.chesslang;

import org.javanile.chesslang.Session;

/**
 *
 * @author totalinnovation
 */
public class Console {
    class Buffer {
	private String b;
	public Buffer(String i) {
	    b = i;
	}
	public String pop() {
	    String o = "";
	    int n = b.indexOf("\n");
	    if (n>0) {
		o = b.substring(0, n);
		b = b.substring(n +1);
		return o;
	    }
	    o = b;
	    b = "";
	    return o;
	}
	public void push(char i) {
	    b+=i;
	}
	public boolean empty() {
	    return b.length()==0;
	}
    }

    private Buffer  fb;
    private Buffer  ib;
    private Session session;
    private String  last;

    public Console() {
	session = new Session();
	fb	= new Buffer(session.inputfile());
	ib	= new Buffer("");
    }

    public String get() {
	if (!fb.empty()) {
	    String o = fb.pop();
	    session.append("[GUI@"+System.currentTimeMillis()+"]: "+o);
	    System.out.println(o);
            last = o;
	    return o;
	}
	if (!ib.empty()) {
	    String o = ib.pop();
	    session.append("[GUI@"+System.currentTimeMillis()+"]: "+o);
            last = o;
	    return o;
	}
	try {
	    char cc='\0';
	    while(cc!='\n') {
		cc = (char)System.in.read();
		ib.push(cc);
	    }
	} catch(Exception e) {
	}
        last = "";
	return "";
    }

    public void put(String s) {
	session.append("[ENG@"+System.currentTimeMillis()+"]: "+s);
	System.out.println(s);
    }

    public boolean like(String s) {
        return last.startsWith(s);
    }


    public String input() {
        return get();
    }

    public void print(String s) {
        put(s);
    }

    public boolean is(String s) {
        return like(s);
    }

    public void clear() {
        System.out.println(((char) 27)+"[2J");
    }
    public void clear(String t) {
        clear();
        line(t);
    }

    public void line(String s) {
        for(int i=0;i<(80-s.length()-8);i++) {
            System.out.print("-");
        }
        System.out.print("--[ "+s+" ]--"+"\n");
    }

    public void table(String[] t) {
        for(int i=0;i<t.length;i++) {
            System.out.print(cell(t[i],20));
        }
        System.out.print("\n");
    }

    public String cell(String s, int w) {
        String r = "";
        for(int i=0;i<(w-s.length());i++) r+=" ";
        return s+r;
    }

    public void quit() {
        System.exit(0);
    }

    public boolean isMove() {
        return last.length()==4;
    }
}
